package com.lyloou.practicerabbitmq.service;

import cn.hutool.json.JSONUtil;
import com.lyloou.practicerabbitmq.entity.Const;
import com.lyloou.practicerabbitmq.entity.Order;
import com.lyloou.practicerabbitmq.entity.OrderDetail;
import com.lyloou.practicerabbitmq.entity.OrderStatus;
import com.lyloou.practicerabbitmq.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @author lilou
 * @since 2021/2/18
 */
@Service
@Slf4j
public class OrderService {
    @Autowired
    @Qualifier("orderDb")
    Map<String, Order> orderDb;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public String order() throws ExecutionException, InterruptedException {
        Order order = newOrder();
        final String orderId = order.getOrderId();

        final CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend(Const.x.order, Const.k.order, order, correlationData);

        // 同步等待；可以设置为异步回调
        CorrelationData.Confirm confirm = correlationData.getFuture().get();
        // 判断发送的消息是否得到broke的确认
        boolean isAcked = confirm.isAck();

        if (!isAcked) {
            throw new RuntimeException("消息中间件服务未确认");
        }

        // 发送延迟等待消息
        rabbitTemplate.convertAndSend(Const.x.ttl, Const.k.ttl, order);

        return orderId;
    }

    private Order newOrder() {
        List<OrderDetail> detailList = new ArrayList<>();
        OrderDetail od = new OrderDetail();
        od.setItemId(Utils.generateItemId());
        od.setItemName("苹果");
        od.setItemPrice(125);
        od.setNum(5);
        detailList.add(od);

        Order order = new Order();
        order.setUserId(Utils.generateUserId());
        order.setOrderId(Utils.generateOrderId());

        order.setStatus(OrderStatus.TO_BE_PAYED);
        order.setDetailList(detailList);
        return order;
    }

    public List<Order> listOrder() {
        return new ArrayList<>(orderDb.values());
    }

    public void pay(String orderId) {
        final Order order = orderDb.get(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 支付
        // doPayed();
        // 设置支付成功状态
        order.setStatus(OrderStatus.PAYED);

        log.info("支付成功，订单详情：{}", JSONUtil.toJsonPrettyStr(order));

        // ！！！不要在此处理ttl，因为很可能会处理掉其它不想干的ttl；要在死信队列中检查订单状态，由死信队列消费者统一处理
        // final Object ttlData = rabbitTemplate.receiveAndConvert(Const.q.ttl);
        // log.info("ttlData:{}", JSONUtil.toJsonPrettyStr(ttlData));
    }
}
